//
//  LLStatusDAL.swift
//  xinlangweibo
//
//  Created by 任玉林 on 16/7/9.
//  Copyright © 2016年 任玉林. All rights reserved.
//

import UIKit

// 清理缓存时间
private let Time: Double = -60*50

class LLStatusDAL: NSObject {
//    CREATE TABLE IF NOT EXISTS "T_Status" (
//    "statusid" INTEGER NOT NULL,
//    "status" TEXT,
//    "userid" INTEGER NOT NULL DEFAULT (datetime('now','localtime')),
//    "createtime" TEXT,
//    PRIMARY KEY("statusid","userid")
//    )
    
    // 删除缓存数据
    class func deleteCache() {
        // 获取当前时间 2016-07-08 10:39:37
        let date = NSDate(timeIntervalSinceNow: Time)
        //
        let df = NSDateFormatter()
        // 指定区域
        df.locale = NSLocale(localeIdentifier: "en_US")
        // 指定格式
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        // 时间字符串
        let timeStr = df.stringFromDate(date)
        print(timeStr)
        // 准备sql
        let sql = "DELETE FROM T_Status WHERE createtime < '\(timeStr)'"
        // 执行sql
        SQLManager.sharedTools.queue.inDatabase { (db) -> Void in
            let result = db.executeUpdate(sql, withArgumentsInArray: nil)
            if result {
                print("删除缓存成功")
            }else {
                print("删除缓存失败")
            }
        }
        
    }
    
    //检查本地是否有缓存数据
    class func checkCache(sinceId: Int64,maxId: Int64,success:SuccessClosure,failure:FailureClosure) {
        
        let reuslt = selectCache(sinceId, maxId: maxId)
        
        if reuslt?.count > 0{
            
            success(response: reuslt)
        }else{
            
            LLNetwordTools.sharedtools.homeLoadData(sinceId, maxId: maxId, success: { (response) -> () in
            
                guard let res = response?["statuses"] as? [[String: AnyObject]]else{
                    
                    return
                }
                
                success(response: res)
                
                saveCache(res)
                
                }, failure: { (error) -> () in
                    
                 failure(error: error )
            })
        }
    }
    
    //查询数据
    class func selectCache(sinceId: Int64,maxId: Int64)->[[String: AnyObject]]?{
        
        guard let userId = LLUserAccountTools.sharedTools.userAccount?.uid else{
            
            return nil
        }
        
        var sql = "SELECT * FROM T_Status\n"
        
        sql += "WHERE userid = \(userId)\n"
        
        if sinceId > 0 {
            
            sql += "AND statusid > \(sinceId)\n"
            
        }
        if maxId > 0 {
            
            sql += "AND statusid <= \(maxId)\n"
            
            
        }
        
        sql += "ORDER BY statusid DESC\n"
        
        sql += "LIMIT 20\n"
        
        
        let result = SQLManager.sharedTools.exeCoder(sql)
        
        var tempArray: [[String: AnyObject]] = [[String: AnyObject]]()
        
        for dict in result {
            
            let data = dict["status"] as! NSData
            
            let dic = try! NSJSONSerialization.JSONObjectWithData(data, options:[]) as! [String: AnyObject]
            
            tempArray.append(dic)
        }
        
        return tempArray
    }
    
    //保存数据
    class func saveCache(status: [[String: AnyObject]]) {
    
    let sql = "INSERT OR REPLACE INTO T_Status(statusid,status,userid) VALUES(?,?,?) "
        
        guard let userId = LLUserAccountTools.sharedTools.userAccount?.uid else{
            
            return
        }
        SQLManager.sharedTools.queue.inTransaction { (db , rollback) -> Void in
            
            for dict in status {
                
                let statusID = dict["id"] as! NSNumber
                
                let statusDict = try! NSJSONSerialization.dataWithJSONObject(dict , options: [])
                
                let result = db.executeUpdate(sql, withArgumentsInArray: [statusID,statusDict,userId])
                
                if result {
                    
                    print("保存成功")
                }else{
                    print("保存失败")
                    
                }
            }
        }
    }

}
